package com.jingyi.framework.util;

import com.jingyi.common.utils.DateUtils;
import com.jingyi.framework.datasource.DynamicDataSource;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;

/**
 * code 生成器
 */
@Component
public class CodeGenerator {
    @Autowired
    private DynamicDataSource dataSource;

    @Value("${jingyi.codeGenerator.step:4}")
    private int codeLength;

    @Value("${jingyi.codeGenerator.step:0001}")
    private String codeFirst;

    public String nextCode(String table){
        String datePrefix = DateUtils.getString(new Date(),DateUtils.YYYYMMDD);
        String maxCode = getCurrentCode(table,datePrefix);
        if(StringUtils.isEmpty(maxCode)){
            return datePrefix+codeFirst;
        }else{
            String curData = maxCode.substring(datePrefix.length());
            int nextLasePhaseCode = Integer.valueOf(curData)+1;
            String nextData = StringUtils.leftPad(Integer.toString(nextLasePhaseCode),codeLength,"0");
            return datePrefix + nextData;
        }
    }

    /**
     * 获取code步长
     * @return
     */
    public int getCodeLength() {
        return this.codeLength;
    }

    /**
     * 获取第一个code
     * @return
     */
    public String getCodeFirst() {
        return this.codeFirst;
    }


    /**
     * 查询当前最大code
     * @param table
     * @param prefix
     * @return
     */
    private String getCurrentCode(String table, String prefix) {
        Connection conn = null;
        try {
            conn = this.dataSource.getConnection();
            String sql = "SELECT max(CODE) MAXCODE from " + table + " where CODE like '" + prefix + "%'";
            PreparedStatement ps = conn.prepareStatement(sql);
            ResultSet set = ps.executeQuery();
            String curr = null;
            if (set.next()) {
                curr = set.getString("maxCode");
            }
            return curr;
        } catch (Exception exception1) {
            new SQLException(exception1.getCause());
        } finally {
            try {
                if (conn != null) {
                    conn.close();
                }
            } catch (Exception exception2) {

            }
        }
        return null;
    }
}
